<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 添加角色,修改角色弹层 -->
      <el-dialog :title="isEdit?'修改角色':'添加角色'" :visible.sync="showDialog" @close="resetForm">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹层 -->
      <el-dialog title="分配权限" :visible.sync="showPerDialog">
        <AssignPer v-if="showPerDialog" :role-id="roleId" @close="showPerDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addRoles, getRoles, delRoles, getRolesDetail, updateRoles } from '@/api/settings'
import AssignPer from './assignPermission.vue'
export default {
  components: {
    AssignPer
  },
  data() {
    return {
      roleId: '',
      showPerDialog: false, // 控制分配权限的弹层显示
      isEdit: false,
      showDialog: false, // 控制添加角色和修改角色的弹层显示
      roleForm: { // 存储用户输入的内容
        name: '',
        description: ''
      },
      list: [], // 保存角色列表
      pageParams: {
        page: 1, // 页码数
        pagesize: 2 // 每页显示的条数
      },
      total: 0, // 获取的角色总数
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hAssign(id) {
      this.roleId = id
      this.showPerDialog = true
    },
    // 弹层关闭重置表单
    resetForm() {
      this.$refs.roleForm.resetFields()
    },
    // 修改
    hEdit(id) {
      this.isEdit = true
      this.showDialog = true
      this.loadRolesDetail(id)
    },
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    async loadRolesDetail(id) {
      const res = await getRolesDetail(id)
      if (res.code !== 10000) return
      this.roleForm = res.data
    },
    // 删除角色
    hDel(id) {
      this.$confirm('你确定要删除吗?').then(async() => {
        const res = await delRoles(id)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 判断当前页面是否只剩一条数据
        if (this.list.length === 1) {
          this.pageParams.page--
          // 注意这个分页最小值只能为1不能小于1所以要进行判断 防止一直减下去 否则会报错
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 重新获取渲染页面
        this.loadRoles()
      }).catch(err => {
        console.log(err)
      })
    },
    hSubmit() {
      // 兜底校验
      this.$refs.roleForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 修改角色
    async doEdit() {
      const res = await updateRoles(this.roleForm)
      if (res.code !== 10000) return
      this.$message.success(res.message)
      // 修改成功关闭弹层
      this.showDialog = false
      // 重新获取数据渲染页面
      this.loadRoles()
    },
    // 添加角色
    async doAdd() {
      // 发送请求
      const res = await addRoles(this.roleForm)
      console.log(res)
      if (res.code !== 10000) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 这里total++是因为已经下面已经请求过服务器的数据了 虽然添加了新数据 但是total还是老数据所以要++
      this.total++
      // 计算最大页码值
      const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
      // 跳转到最后一页
      this.pageParams.page = maxPage
      this.loadRoles()
      this.showDialog = false
    },
    handleSizeChange(val) {
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.loadRoles()
      console.log(`当前页: ${val}`)
    },
    // 加载角色列表
    async loadRoles() {
      const res = await getRoles(this.pageParams)
      console.log(res)
      if (res.code !== 10000) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.list = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
